package com.nativetalk.service.three.book.search;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.book.*;
import com.nativetalk.bean.member.DiscountCoupon;
import com.nativetalk.bean.member.MembNewUserScholarship;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.setmeal.TdNtMembSetmealList;
import com.nativetalk.bean.rongyun.RongCloudConfig;
import com.nativetalk.bean.rongyun.TokenResult;
import com.nativetalk.bean.teacher.TdNtTeacherIndex;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.rongCloud.RongCloud;
import com.nativetalk.common.util.DateUtil;
import com.nativetalk.common.util.JsonUtil;
import com.nativetalk.dao.*;
import com.nativetalk.dto.weike.WeikeSubscription;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Reader;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lizhun on 16/8/2.
 */
@Service
public class ThreeBookSearchServiceImpl implements ThreeBookSearchService {
    private static Logger logger = Logger.getLogger(ThreeBookSearchServiceImpl.class);
    private static String WAIJIAOJUN_URL = "file.waijiaojun.com/";

    @Resource
    private TdNtBookCourseDao tdNtBookCourseDao;
    @Resource
    private TdNtTeacherDao tdNtTeacherDao;
    @Resource
    private TdNtMembSetmealDao tdNtMembSetmealDao;
    @Resource
    private TdNtCommentDao tdNtCommentDao;
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private RongCloudConfig rongCloudConfig;
    @Resource
    private TdNtReserveDao tdNtReserveDao;
    @Resource
    private MembNewUserScholarshipDao membNewUserScholarshipDao;
    @Resource
    private DiscountCouponDao discountCouponDao;

    @Override
    public TdNtBookCourse findBook(TdNtBookCourse tdNtBookCourse) {
        String logInfo = this.getClass().getName() + ":findBook:";
        logger.info("======" + logInfo + "begin======");
        TdNtBookCourse bookCourse = null;
        try {
            bookCourse = tdNtBookCourseDao.findBook(tdNtBookCourse);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return bookCourse;
    }

    @Override
    public RetInfo findBookByMembId(Map<String, Object> map) {
        // 类路径+方法名
        logger.info(Constants.prefix_in + JsonUtil.toJson(map));
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> result = new HashMap<>();
            int currentPage = Integer.valueOf(map.get("currentPage").toString());
            int pageSize = Integer.valueOf(map.get("pageSize").toString());
            int totalPage;//总页数
            int totalRecord = tdNtMembSetmealDao.findFinsihTdNtMembSetmealListSize((Integer) map.get("memb_id"));
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    currentPage = 1;
                }
                map.put("currentPage", (currentPage - 1) * pageSize);

                List<TdNtMembSetmealList> tdNtMembSetmealLists = tdNtMembSetmealDao.findFinsihTdNtMembSetmealListPage(map);

                result.put("setmeals", tdNtMembSetmealLists);
                result.put("totalPage", totalPage);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("获取课程");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("暂无该课程");
            }
            retInfo.setObj(result);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("====== end ======");
        return retInfo;
    }

    //可以预约的课程，即将过期的排在最前面
    @Override
    public RetInfo membBookableCourse(Integer memb_id) {
        // 类路径+方法名
        RetInfo retInfo = new RetInfo();
        try {
            List<TdNtMembSetmealList> courseList = tdNtMembSetmealDao.findMembBookableCourse(memb_id);
            retInfo.setObj(courseList);
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            if (courseList == null || courseList.size() == 0) {
                retInfo.setTip("无可预约课程");
            } else {
                retInfo.setTip("获取可预约课程成功");
            }

        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("====== end ======");
        return retInfo;
    }

    @Override
    public RetInfo findBookByTeaId(Map<String, Object> map) {
        String logInfo = this.getClass().getName() + ":findBookByTeaId:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> result = new HashMap<>();
            int currentPage = Integer.valueOf(map.get("currentPage").toString());
            int pageSize = Integer.valueOf(map.get("pageSize").toString());
            int totalPage;//总页数
            int totalRecord = tdNtBookCourseDao.findBookByTeaIdState(map);//总条数
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    currentPage = 1;
                }
                map.put("currentPage", (currentPage - 1) * pageSize);

                List<TdNtBookCourseTeacher> tdNtBookCourseMembers = tdNtBookCourseDao.findBookByTeaIdStatePage(map);

                result.put("book", tdNtBookCourseMembers);
                result.put("totalPage", totalPage);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("获取课程");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("暂无该课程");
            }
            retInfo.setObj(result);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findBookByState(Map<String, Object> map) {
        String logInfo = this.getClass().getName() + ":findBookByState:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            Map<String, Object> result = new HashMap<>();
            int currentPage = Integer.valueOf(map.get("currentPage").toString());
            int pageSize = Integer.valueOf(map.get("pageSize").toString());
            int totalPage;//总页数
            int totalRecord = tdNtBookCourseDao.findBookByState(map);//总条数
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    currentPage = 1;
                }
                map.put("currentPage", (currentPage - 1) * pageSize);
                List<TdNtBookCourseTeacher> tdNtBookCourseMembers = tdNtBookCourseDao.findBookByStatePage(map);
                result.put("book", tdNtBookCourseMembers);
                result.put("totalPage", totalPage);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("获取可接单列表成功");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("暂无可接单课程表");
            }
            retInfo.setObj(result);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    @Override
    public RetInfo findBookWeek(int book_cou_id) {
        String logInfo = this.getClass().getName() + ":findBookDetailTeacherConnent:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取数据成功");
            Map<String, Object> map = new HashMap<>();
            List<TdNtBookCourseWeek> tdNtBookCourseWeeks = tdNtBookCourseDao.findBookWeek(book_cou_id);
            map.put("week", tdNtBookCourseWeeks);
            TdNtBookCourse tdNtBookCourse = tdNtBookCourseDao.findBookById(book_cou_id);
            map.put("frequency", tdNtBookCourse.getFrequency());
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Override
    public RetInfo findBookWeekHis(int book_cou_id) {
        String logInfo = this.getClass().getName() + ":findBookWeekHis:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            retInfo.setMark(ValidationMessages.getValue("MARKYES"));
            retInfo.setTip("获取数据成功");
            Map<String, Object> map = new HashMap<>();
            List<TdNtBookCourseWeekHis> tdNtBookCourseWeekHises = tdNtBookCourseDao.findBookWeekHis(book_cou_id);
            map.put("week", tdNtBookCourseWeekHises);
            TdNtBookCourse tdNtBookCourse = tdNtBookCourseDao.findBookById(book_cou_id);
            TdNtTeacherIndex tdNtTeacherIndex = tdNtTeacherDao.findTdNtTeacherIndex(tdNtBookCourse.getTea_id());
            map.put("tea_head_portrait", tdNtTeacherIndex.getTea_head_portrait());
            map.put("tea_name", tdNtTeacherIndex.getTea_name());
            retInfo.setObj(map);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }

    @Resource
    private WeikeSubscriptionDao weikeSubscriptionDao;

    @Override
    public RetInfo findBookByUnfinishMembId(Map<String, Object> map) {
        String logInfo = this.getClass().getName() + ":findBookByUnfinishMembId:";
        // 类路径+方法名
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {

            Map<String, Object> result = new HashMap<>();
            int currentPage = Integer.valueOf(map.get("currentPage").toString());
            int pageSize = Integer.valueOf(map.get("pageSize").toString());
            int totalPage;//总页数
            int totalRecord = tdNtBookCourseDao.findBookByUnfinishMembIdState(map);//总条数
            if (totalRecord > 0) {
                if (totalRecord % pageSize == 0) {
                    totalPage = totalRecord / pageSize;
                } else {
                    totalPage = (totalRecord / pageSize) + 1;
                }
                if (currentPage >= totalPage) {
                    currentPage = totalPage;
                }
                if (currentPage <= 1) {
                    currentPage = 1;
                }
                map.put("currentPage", (currentPage - 1) * pageSize);

                List<TdNtBookCourseMemberUn> tdNtBookCourseMembers = tdNtBookCourseDao.findBookByUnfinishMembIdStatePage(map);

                result.put("book", tdNtBookCourseMembers);
                result.put("totalPage", totalPage);
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip("获取课程");
            } else {
                retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                retInfo.setTip("暂无该课程");
            }
            retInfo.setObj(result);
        } catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(), e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }


    // 2. 展示所购买的课程：
    //• 无课程：空状态（图1）；
    //• 一个课程：隐藏“更多”入口；
    //• 二个及以上课程：
    //•   a.未约过课："我的"展示最新购买的课程；
    //•   b.约过课：“我的”展示上课次数最多的课程；
    //• 点击“更多”展示同上版本“我的课程”页
    public void index(TdNtMember tdNtMember, Map<String, Object> map) {
        // 1. 查询购买的总课时和已完成课时(课时学习进度条：进度条同步已学的课时；“剩余课时”展示总的课时量；)
        //查询学生购买的套餐列表
        Map<String, Object> params = new HashMap<>();

        String appKey = rongCloudConfig.getAppkey();
        String appSecret = rongCloudConfig.getSecret();
        TokenResult tokenResult = null;
        params.put("currentPage", 0);
        params.put("pageSize", 1000);
        params.put("memb_id", tdNtMember.getMemb_id());
        Integer allClassHours = 0; //购买的总课时
        Integer allClassHoursFinished = 0;//已完成课时
        try {
            List<TdNtMembSetmealList> tdNtMembSetmealLists = tdNtMembSetmealDao.findFinsihTdNtMembSetmealListPage(params);
            for (int i = 0; i < tdNtMembSetmealLists.size(); i++) {
                TdNtMembSetmealList membSetmeal = tdNtMembSetmealLists.get(i);
                allClassHours = allClassHours + membSetmeal.getCou_size();
                // 过期的套餐算已完成课时数
                if (membSetmeal.getEnd_time().getTime() < System.currentTimeMillis()) {
                    // 过期
                    allClassHoursFinished = allClassHoursFinished + membSetmeal.getCou_size();
                } else {
                    allClassHoursFinished = allClassHoursFinished + membSetmeal.getSet_finish_size();
                }
            }
            TdNtMember member = tdNtMemberDao.findMember(tdNtMember.getMemb_id());
            if (member.getRongcloud_token() == null || member.getRongcloud_token() == "") {
                // 获取融云 Token 方法
                Reader reader = null;
                RongCloud rongCloud = RongCloud.getInstance(appKey, appSecret);
                String memb_id = "student" + member.getMemb_id();
                String memb_head_portraituri = member.getMemb_head_portrait();
                if (!memb_head_portraituri.contains("http")) {
                    memb_head_portraituri = WAIJIAOJUN_URL + memb_head_portraituri;
                }
                tokenResult = rongCloud.user.getToken(memb_id, tdNtMember.getMemb_name(), memb_head_portraituri);
                tdNtMemberDao.updateRongCloudToken(tokenResult.token, Integer.valueOf(tdNtMember.getMemb_id()));
                if (tokenResult.getToken() != null && tokenResult.getToken() != "") {
                    map.put("rongCloudToken", tokenResult.getToken());
                }
                logger.info(tokenResult.toString());
            } else {
                map.put("rongCloudToken", member.getRongcloud_token());
            }
            //判断用户有没有领取优惠券，没有的话默认领取
            int reserve_package = tdNtMemberDao.findUseReservePackage(tdNtMember.getMemb_id());
            Date date = DateUtil.createDate("2018-06-01 00:00:00");
            if (reserve_package == 0 && tdNtMember.getMemb_register_time().after(date)) {
                //用户领取红包
                // 1. 添加红包领取记录
                MembNewUserScholarship pojo = new MembNewUserScholarship(tdNtMember.getMemb_id());
                membNewUserScholarshipDao.insert(pojo);

                // 2.添加到优惠券表中
                DiscountCoupon discountCoupon = new DiscountCoupon();
                discountCoupon.setCourse_type(1);
                discountCoupon.setMemb_id(tdNtMember.getMemb_id());
                discountCoupon.setDeleted(0);
                discountCoupon.setOver((double) 0);
                discountCoupon.setSubtract((double) 120);
                discountCoupon.setDiscount_state(0);
                discountCouponDao.insertDiscountCoupon(discountCoupon);
            }
            Integer all_count = tdNtReserveDao.findAllPunchedCount(tdNtMember.getMemb_id());
            map.put("all_punched_count", all_count);
            map.put("token", member.getToken());
            map.put("allClassHours", allClassHours);//购买的总课时
            map.put("allClassHoursFinished", allClassHoursFinished);//已完成课时

            if (tdNtMembSetmealLists != null && tdNtMembSetmealLists.size() > 0) {
                map.put("buyCourseTop1", tdNtMembSetmealLists.get(0));
            } else {
                map.put("buyCourseTop1", null);
            }

            if (tdNtMembSetmealLists != null) {
                map.put("buyCourseSize", tdNtMembSetmealLists.size());
            } else {
                map.put("buyCourseSize", 0);
            }
            //判断是否是会员，以及会员有效期至
            WeikeSubscription weikeSubscriptionList = weikeSubscriptionDao.findValidSubscribedByMembId(tdNtMember.getMemb_id());
            if (weikeSubscriptionList != null) {
                map.put("isVip", 1);
                map.put("endTime", weikeSubscriptionList.getSubscription_end_time());
            } else {
                map.put("isVip", 0);
            }
        } catch (Exception e) {
            //记录错误日志
            logger.error(e.getMessage(), e);

        }
    }
}
